package com.itheima.balance;

import java.util.ArrayList;

public class WRR {
    //所有节点的列表
    ArrayList<Node> list ;
    //总权重
    int total;

    //初始化节点列表
    public WRR(String nodes){
        String[] ns = nodes.split(",");
        list = new ArrayList<>(ns.length);
        for (String n : ns) {
            String[] n1 = n.split("#");
            int weight = Integer.valueOf(n1[1]);
            list.add(new Node(n1[0],weight));
            total += weight;
        }
    }

    //获取当前节点
    Node getCurrent(){
        //执行前，current加权重
        for (Node node : list) {
            node.currentWeight += node.weight;
        }

        //遍历，取权重最高的返回
        Node current = list.get(0);
        int i = 0;
        for (Node node : list) {
            if (node.currentWeight > i){
                i = node.currentWeight;
                current = node;
            }
        }
        return current;
    }

    //响应
    void request(){
        //获取当前节点
        Node node = this.getCurrent();
        //第一列，执行前的current
        System.out.print(list.toString()+"---");
        //第二列，选中的节点开始响应
        System.out.print(node.name+"---");
        //响应后，current减掉total
        node.currentWeight -= total;
        //第三列，执行后的current
        System.out.println(list);
    }

    public static void main(String[] args) {
        WRR wrr = new WRR("a#4,b#2,c#1");
        //7次执行请求，看结果
        for (int i = 0; i < 7; i++) {
            wrr.request();
        }
    }

    class Node{
        int weight,currentWeight;
        String name;
        public Node(String name,int weight){
            this.name = name;
            this.weight = weight;
            this.currentWeight = 0;
        }

        @Override
        public String toString() {
            return String.valueOf(currentWeight);
        }
    }
}
